package com.whiteape.book.presenter;

import com.hwangjr.rxbus.RxBus;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.BookDetailContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.ui.base.RxPresenter;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;

import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by newbiechen on 17-5-4.
 */

public class BookDetailPresenter extends RxPresenter<BookDetailContract.View>
        implements BookDetailContract.Presenter {
    private static final String TAG = "BookDetailPresenter";
//    private String bookId;

    @Override
    public void refreshBookDetail(CollectionMediaBean collectionMediaBean) {
//        this.bookId = bookId;
        refreshBook(collectionMediaBean);

//        refreshComment();
//        refreshRecommend();

    }

    @Override
    public void addToBookShelf(CollectionMediaBean collectionMediaBean) {
        collectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        if (!collectionMediaBean.getMediaChapterList().isEmpty()) {
            //存储收藏
            MediaStorageManager.getInstance()
                    .saveCollectionMediaWithAsync(collectionMediaBean);

            mView.succeedToBookShelf();
            RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, collectionMediaBean);
            return;
        }

        collectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        SiteSourceBean siteSourceBean = collectionMediaBean.getSiteSourceBean();

        Disposable disposable = WebMediaManager.getInstance()
                .getCatalog(siteSourceBean, collectionMediaBean)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(
                        (d) -> mView.waitToBookShelf() //等待加载
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        beans -> {

//                            //设置 id
//                            for (MediaChapterBean bean : beans) {
//                                bean.setId(MD5Utils.strToMd5By16(bean.getLink()));
//                            }

                            //设置目录
                            collectionMediaBean.setMediaChapterList(beans);
                            //存储收藏
                            MediaStorageManager.getInstance()
                                    .saveCollectionMediaWithAsync(collectionMediaBean);

                            mView.succeedToBookShelf();
                            RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, collectionMediaBean);
                        }
                        ,
                        e -> {
                            mView.errorToBookShelf();
                            LogUtils.e(e);
                        }
                );
        addDisposable(disposable);
    }

    private void refreshBook(CollectionMediaBean collectionMediaBean) {
        WebMediaManager
                .getInstance()
                .getMediaInfo(collectionMediaBean)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(new SingleObserver<CollectionMediaBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(CollectionMediaBean value) {
                        mView.finishRefresh(value);
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.showError();
                    }
                });
    }
//
//    private void refreshComment() {
//        Disposable disposable = RemoteRepository
//                .getInstance()
//                .getHotComments(bookId)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(
//                        (value) -> mView.finishHotComment(value)
//                );
//        addDisposable(disposable);
//    }
//
//    private void refreshRecommend() {
//        Disposable disposable = RemoteRepository
//                .getInstance()
//                .getRecommendBookList(bookId, 3)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(
//                        (value) -> mView.finishRecommendBookList(value)
//                );
//        addDisposable(disposable);
//    }




    public void updateWebCatalog(SiteSourceBean siteSourceBean, CollectionMediaBean mediaBean) {
        LogUtils.d("loadWebCatalog");
        Disposable disposable = WebMediaManager.getInstance()
                .getCatalog(siteSourceBean, mediaBean)
//                .doOnSuccess(new Consumer<List<MediaChapterBean>>() {
//                    @Override
//                    public void accept(List<MediaChapterBean> bookChapterBean) throws Exception {
//                        //进行设定BookChapter所属的书的id。
//                        LogUtils.d("loadWebCatalog, accept, bookChapterBean is " + bookChapterBean);
//                        for (MediaChapterBean bookChapter : bookChapterBean) {
//                            bookChapter.setId(MD5Utils.strToMd5By16(bookChapter.getLink()));
//                            bookChapter.setLink(bookChapter.getLink());
//                            bookChapter.setMediaId(mediaBean.getId());
//                        }
//                    }
//                })
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        beans -> {
                            LogUtils.d("loadWebCatalog, onSuccess, beans is " + beans);
                            mView.updateCatalog(beans);
                        }
                        ,
                        e -> {
                            //TODO: Haven't grate conversation method.
                            LogUtils.e(e);
                            e.printStackTrace();

                        }
                );
        addDisposable(disposable);
    }

}
